package controller

import (
	"gin_project/common"
	"gin_project/model"
	"gin_project/util"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
)

func Register(ctx *gin.Context) {
	DB := common.GetDB()
	name := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":     422,
			"msg":      "手机号是11位！",
			"length":   len(telephone),
			"password": password,
		})
		return
	}
	if len(password) <= 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "密码不能少于6位！！",
		})
		return
	}
	//如果没有名称则随机赋值一个字符串
	if len(name) == 0 {
		name = util.RandomString(10)
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"name": name,
		})
	}
	if util.IsTelephoneExist(DB, telephone) {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "用户已经存在不用注册了！",
		})
		return
	}
	//接下来就是用户存在的情况了

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(422, gin.H{
			"code": 500,
			"msg":  "加密出现错误",
		})
	}
	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  string(hashedPassword),
	}
	DB.Create(&newUser)

	ctx.String(200, "注册成功！Welcome here!!")

}

func Login(ctx *gin.Context) {
	//	获取参数
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code":     422,
			"msg":      "手机号是11位！",
			"length":   len(telephone),
			"password": password,
		})
		return
	}
	if len(password) <= 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "密码不能少于6位！！",
		})
		return
	}
	//	数据验证
	//--判断密码是否存在
	var user model.User
	DB := common.GetDB()
	//引入DB

	DB.Where("telephone=?", telephone).First(&user)
	if user.ID == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "笑死，用户根本不存在",
		})

	}

	//	密码是否正确
	if errPassword := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); errPassword != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	//发放token
	token := "11"
	ctx.JSON(200, gin.H{
		"code": 200,
		"data": gin.H{
			"token": token,
		},
	})

	//	发放token给前端

}
